<template>
  <view @click="closeList">
    <l-background />
    <l-tab-bar id="tabBar" :tabs="tabs" :active-inx.sync="activeInx" />

    <swiper :style="{height:height+'px'}" :current="activeInx" :duration="300" @change="onswiperchange">
      <swiper-item>
        <scroll-view :style="{height:sHeight+'px'}" scroll-y>
          <view class="add-new-container">
            <!-- 选择模板 -->
            <view class="card margin-bottom-14">
              <order-module-choose v-model="module" @change="module=$event" />
            </view>

            <!-- 订单基本信息 -->
            <view class="card margin-bottom-14">
              <order-info-module :data="form" :module="module" type="edit" @update="updateFormData" @changeDate="setDate" />
            </view>

            <!-- 客户信息 -->
            <view class="card customer-module margin-bottom-14">
              <order-customer-module ref="customerModule" :data="form" @update="updateFormData" />
            </view>

            <!-- 车辆信息 -->
            <view class="margin-bottom-14">
              <order-vehicle-module
                v-for="(item,index) in form.orderVehicleList"
				:formInfo="form"
                :key="index"
                ref="vehicleModule"
                :data="item"
                :inx="index"
                :show-del="showDel"
                :start-date="form.startDate"
                :end-date="form.endDate"
                :show-platform-driver="showPlatformDriver"
                :vehicle-add="vehicleAdd"
                @choose="choose($event,index)"
                @delVehicle="delVehicle(index)"
                @update="updateVehicleData($event,index)"
              />
            </view>

            <tui-button v-if="!vehicleAdd" type="gray-black" @click="addVehicle">
              <text class="tbb-tianjia1 text-bold text-34 margin-right-10" />
              <text class="text-34">添加车辆</text>
            </tui-button>
          </view>
        </scroll-view>
      </swiper-item>
      <swiper-item>
        <scroll-view :style="{height:sHeight+'px'}" scroll-y>
          <view class="add-new-container">
            <view class="card">
              <order-other-module :data="form" @update="updateFormData" />
            </view>
          </view>
        </scroll-view>
      </swiper-item>
    </swiper>

    <safe-area-bottom id="safe" />

    <l-bottom-button text="提交订单" :disabled="!canCreate" @click="creatOrder">
      <view v-if="showProtocol" class="padding-bottom-20">
        <l-check-box v-model="isRead">
          <view slot="after" class="flex-row align-center" @click="isRead=!isRead">
            <text class="text-24 color-t3">我已阅读并同意</text>
            <text class="text-24 color-primary" @click.stop="showAgreement = true">《{{ name }}司机协议》</text>
          </view>
        </l-check-box>
      </view>
    </l-bottom-button>

    <tui-modal
      :show="showModal"
      title="提示"
      content="当前司机该时间段处于离职或休假状态"
      :button="[{text:'确定'}]"
      @click="showModal=false"
      @cancel="showModal=false"
    />
    <first-create v-if="firstCreateOrder" tab-name="订单信息" placeholder="点击可填写更多订单内容" />
    <driver-agreement :show.sync="showAgreement" @confirm="isRead=true" />

    <bz-date-picker :value="start" :days="92" :min-time="minStartDate" type="start" :default-time="startDate" :minute-step="10" @confirm="startDateConfirm" @cancel="close('start')" @close="close('start')" />
    <bz-date-picker v-if="endTimeShow" :value="end" :days="92" :min-time="form.startDate.replace(/-/g,'/') || minStartDate" type="end" :default-time="endDate" :minute-step="10" @confirm="endDateConfirm" @cancel="close('end')" @close="close('end')" />
  </view>
</template>

<script>
import OrderModuleChoose from '../components/order-module-choose/order-module-choose'
import OrderInfoModule from '../components/order-info-module/order-info-module'
import OrderCustomerModule from '../components/order-customer-module/order-customer-module'
import OrderVehicleModule from '../components/order-vehicle-module/order-vehicle-module'
import OrderOtherModule from '../components/order-other-module/order-other-module'
import FirstCreate from '../components/first-create/first-create'
import DriverAgreement from '../components/driver-agreement/driver-agreement'
import { mapGetters, mapMutations } from 'vuex'
import { dateFormat, loading, checkDate } from '@/common/util'
import { getHookOrderDetail } from '@/common/api/order'
import { getProductListCv } from '@/common/api/car.js'
import { bindJudgmentVehicle, bindJudgment, bindDriver, orderGetCarList } from '@/common/api/car'
import { products } from '../index'
import { addInternalJson } from '../api'
import { name } from '@/common/config'
import { numericTypeCheck,numberTypeCheck } from '@/common/util.js'
export default {
  name: 'AddNew',
  components: {
    OrderModuleChoose,
    OrderInfoModule,
    OrderCustomerModule,
    OrderVehicleModule,
    OrderOtherModule,
    FirstCreate,
    DriverAgreement
  },
  data() {
    const today = new Date()
    const tomorrow = today.getTime() + (1000 * 60 * 60 * 24)

    const date = new Date(tomorrow)
    date.setMinutes(0)
    const start = date.setHours(6)
    const end = date.setHours(21)

    const minStart = new Date(today.setDate(today.getDate() - 30))
    minStart.setHours(0)
    minStart.setMinutes(0)
    const minStartDate = dateFormat(minStart, 'YYYY/MM/DD hh:mm')
    const startDate = dateFormat(new Date(start), 'YYYY/MM/DD hh:mm')
    const endDate = dateFormat(new Date(end), 'YYYY/MM/DD hh:mm')
    return {
      loading: null,
      tabs: [
        { title: '用车信息' },
        { title: '订单信息' }
      ],
	  productId:'',
      activeInx: 0,
      showModal: false,
      showAgreement: false,
      vehicleAdd: false,
      hookId: '', // 获客订单Id
      module: 0, // 模板类型 0:模板一  1:模板二
      form: {
        companyHookOrderId: '', // 获客订单Id
        startDate: '', // 出发时间
        endDate: '', // 结束时间
        from: '', // 出发点请求数据
        fromLat: '', // 出发点请求数据
        fromLnt: '', // 出发点请求数据
        stopSite: [], // 停靠点
        to: '', // 到达点请求数据
        toLat: '', // 到达点请求数据
        toLnt: '', // 到达点请求数据
        itinerary: '', // 行程路线
        payWay: 3, // 支付方式
        username: '', // 乘车客户名称
        customerPhone: '', // 乘车客户电话
        internalProductType: products[0].value, // 产品
        internalProductTypeLabel: products[0].name, // 产品名称
        pickUpNum: 1, // 接送趟次
        itineraryUrl: '', // 行程单
        contact: '', // 联系人/导游
        phone: '', // 乘车联系人电话
        remark: '', // 订单备注
        isTaoTuan: false, // 套团
        roundType: 1, // 出团往返类型 1：单程，2：往返
        orderVehicleList: [], // 车辆信息
        outwardVehicleList: [] // 外调车辆信息
      },
      vehicleInfo: { // 车辆信息
        driverId: '', // 司机id
        driverName: '', // 司机名称
        driverRemark: '', // 司机备注
        driverSubsidyAmount: '', // 司机补助
        passengers: '', // 乘车人数
        realPrice: '', // 车费
        vehicleName: '', // 车辆名称
        vehicleId: '', // 车辆id
        platformDriverFee: '', // 司机费用
        vehicleType: 0, // 车辆类型 0-自有车辆 1-外调车辆
        driverType: 0, // 司机类型 0-自有司机 1-平台司机 2-外调司机
        // 外调表单
        autoCompanyName: '', // 车企名称
        seatNum: '', // 座位数
        driverPhone: '', // 司机电话
        payWay: 3, // 支付方式
        outwardRealPrice: '' // 外调车辆费用
      },
      chooseInx: 0, // 修改信息车辆下标
      minStartDate, // 最小开始时间
      startDate, // 默认开始时间
      endDate, // 默认结束时间
      endTimeShow: true, // 是否加载结束时间选择框
      start: false, // 开始时间弹窗
      end: false, // 结束时间弹窗
      isRead: false, // 是否已读协议
      height: 0, // 内容高度
      canCreate: true, // 是否可创建
      mustList: [ // 校验列表
        { placeholder: '请选择出发时间', value: 'startDate', condition: () => true },
        { placeholder: '请选择结束时间', value: 'endDate', condition: () => true },
        { placeholder: '请输入行程路线', value: 'itinerary', condition: () => this.module === 0 },
        { placeholder: '请选择出发地', value: 'from', condition: () => this.module === 1 },
        { placeholder: '请选择目的地', value: 'to', condition: () => this.module === 1 },
        { placeholder: '请输入客户名称', value: 'username', condition: () => this.form.payWay == 3 },
        { placeholder: '请输入接送趟次', value: 'pickUpNum', condition: () => this.form.internalProductType == 3 }
      ],
      name
    }
  },
  computed: {
    // 是否展示删除按钮
    showDel() {
      return this.form.orderVehicleList.length > 1
    },
    // 已选司机列表
    driverList() {
      return this.form.orderVehicleList.map(item => item.driverId)
    },
    // 已选车辆列表
    vehicleList() {
      return this.form.orderVehicleList.map(item => item.vehicleId)
    },
    // 滚动区域高度
    sHeight() {
      return this.height - this.px()
    },
    // 是否显示平台司机
    showPlatformDriver() {
      if (this.form.endDate) {
        const now = new Date().getTime()
        const end = new Date(this.form.endDate.replace(/-/g, '/')).getTime()
        return end > now
      }
      return true
    },
    // 是否展示协议
    showProtocol() {
      for (let i = 0; i < this.form.orderVehicleList.length; i++) {
        const item = this.form.orderVehicleList[i]
        if (!item.vehicleType && item.driverType == 1) {
          return true
        }
      }
      return false
    },
    ...mapGetters({
      chooseVehicleInfo: 'chooseVehicleInfo',
      chooseDriverInfo: 'chooseDriverInfo',
      firstCreateOrder: 'firstCreateOrder'
    })
  },
  watch: {
    showProtocol(e) {
      let num = this.px(56)
      if (num % 2) num--
      if (e) {
        this.height -= num
      } else {
        this.height += num
      }
    }
  },
  onShow() {
    this.setVehicle()
    this.setDriver()
  },
  onLoad(options) {
	this.getId(options.pType)

    this.addVehicle()
    if (options.hookId) {
      this.hookId = options.hookId
      this.getHookOrder()
    }
    if (options.type) {
      this.vehicleAdd = true
    }
  },
  mounted() {
    this.setHeight()
  },
  methods: {
	// 获取pid
	getId(type){
		getProductListCv().then(res =>{
			  console.log(res);
			  let list = res[1].data.data
			  for (const item of list) {
				if (item.type == type) this.productId = item.id
			  }
		})
	},
    // 设置高度
    setHeight() {
      const wHeight = this.sysInfo().windowHeight
      this.getElementInfo('#tabBar', res => {
        this.height = wHeight - res.height
        this.getElementInfo('#safe', res => {
          this.height -= res.height
        })
      })
    },
    // 轮播滑动
    onswiperchange(e) {
      this.activeInx = e.target.current || e.detail.current
    },
    // 更新表单信息
    updateFormData(e) {
      Object.assign(this.form, e)
    },
    // 显示修改时间弹窗
    setDate(e) {
      this[e] = true
    },
    // 关闭修改时间弹窗
    close(e) {
      this[e] = false
    },
    // 修改开始时间
    startDateConfirm(e) {
      this.form.startDate = dateFormat(e, 'YYYY-MM-DD hh:mm')
      this.startDate = dateFormat(e, 'YYYY/MM/DD hh:mm',)
      this.endDate = dateFormat(new Date(this.startDate).setHours(new Date(this.startDate).getHours() + 11), 'YYYY/MM/DD hh:mm')
      this.endTimeShow = false
      setTimeout(() => {
        this.endTimeShow = true
      }, 100)
      this.start = false
      this.changeDate()
    },
    // 修改结束时间
    endDateConfirm(e) {
      this.form.endDate = dateFormat(e, 'YYYY-MM-DD hh:mm')
      this.endDate = dateFormat(e, 'YYYY/MM/DD hh:mm')
      this.end = false
      this.changeDate()
    },
    // 修改时间改变车辆状态
    async changeDate() {
      const [err, res] = await orderGetCarList({
        page: 1,
        limit: 1000,
        order: 'auto',
        startDate: this.form.startDate,
        seatAmount: this.form.passengers,
        nextDate: this.form.endDate,
        status: this.form.isTaoTuan ? '' : '0'
      })
      if (!this.$http.errorCheck(err, res)) return false
      let carLists = res.data.data.records
      if (!carLists) {
        carLists = []
      }
      const carIds = carLists.map(item => item.id)
      const list = []
      this.form.orderVehicleList.forEach(item => {
        if (item.vehicleId && carIds.indexOf(item.vehicleId) != -1) list.push(item)
      })
      if (list.length) this.form.orderVehicleList = list
      else if (this.form.orderVehicleList.length) {
        const obj = this.form.orderVehicleList[0]
        obj.driverId = ''
        obj.driverName = ''
        obj.vehicleName = ''
        obj.vehicleId = ''
      }
    },
    // 新增车辆按钮
    addVehicle() {
      const vehicleData = this.copyData(this.vehicleInfo)
      this.form.orderVehicleList.push(vehicleData)
    },
    // 选择车辆/司机
    choose(e, index) {
      this.chooseInx = index
      const status = this.form.isTaoTuan ? '' : '0'
      const list = JSON.stringify(this[e.type + 'List'])
      const query = '&startDate=' + this.form.startDate +
          '&endDate=' + this.form.endDate +
          '&status=' + status +
          '&chosen=' + list
      this.jump(e.url + query)
    },
    // 更新车辆模块信息
    updateVehicleData(e, key) {
      Object.assign(this.form.orderVehicleList[key], e)
    },
    // 删除车辆
    delVehicle(i) {
      this.form.orderVehicleList.splice(i, 1)
    },
    // 修改车辆信息
    setVehicle() {
      if (this.chooseVehicleInfo) {
        const inx = this.chooseInx
        const data = {}
        Object.assign(data, this.chooseVehicleInfo)
        for (let i = 0; i < this.form.orderVehicleList.length; i++) {
          const item = this.form.orderVehicleList[i]
          if (data.driverId && item.driverId && data.driverId === item.driverId) {
            data.driverId = ''
            data.driverName = ''
          }
        }
        Object.assign(this.form.orderVehicleList[inx], data)
        if (data.showModule) {
          this.showModal = true
        }
        if (this.chooseVehicleInfo.date) {
          this.form.startDate = this.chooseVehicleInfo.date + ' 06:00'
          this.form.endDate = this.chooseVehicleInfo.date + ' 21:00'
          this.startDate = this.form.startDate.replace(/-/g, '/')
          this.endDate = this.form.endDate.replace(/-/g, '/')
        }
        this.setChooseVehicleInfo(null)
      }
    },
    // 修改司机信息
    setDriver() {
      const inx = this.chooseInx
      if (this.chooseDriverInfo) {
        Object.assign(this.form.orderVehicleList[inx], this.chooseDriverInfo)
        this.setChooseDriverInfo(null)
      }
    },
    // 关闭客户名称/手机号/车辆列表
    closeList() {
      this.$refs.customerModule.showUsername = false
      this.$refs.customerModule.showCustomerPhone = false
      this.$refs.vehicleModule.forEach(vehicleModule => {
        vehicleModule.showAutoCompanyName = false
      })
    },
    // 下单按钮
    async creatOrder() {
      if (this.checkForm()) {
		if(this.form.pickUpNum && !numericTypeCheck(this.form.pickUpNum,'接送趟次只能为整数')){
			return false
		}
	
        if (this.module) {
          this.form.itinerary = ''
        } else {
          this.form.from = ''
          this.form.fromLat = ''
          this.form.fromLnt = ''
          this.form.stopSite = []
          this.form.to = ''
          this.form.toLat = ''
          this.form.toLnt = ''
        }
        this.loading = loading('加载中...')
        this.canCreate = false
        const vehicleList = this.form.orderVehicleList.filter(item => { return item.vehicleType == 0 })
        for (let i = 0; i < vehicleList.length; i++) {
          const item = vehicleList[i]
          if (!item.driverType) {
            /* await this.request(bindJudgment, {
              driverId: item.driverId,
              vehicleId: item.vehicleId,
              type: 1
            })*/
            await this.request(bindJudgmentVehicle, {
              driverId: item.driverId,
              vehicleId: item.vehicleId,
              startDate: this.form.startDate,
              endDate: this.form.endDate
            })
            // await this.bindLinkDriver(item)
            console.log('wait' + i)
          }
        }
        console.log('finish')
        await this.addOrder()
		this.setSelectedFromTo({to: null, from: null})
        this.canCreate = true
      }
    },
    // 表单验证
    checkForm() {
      for (let i = 0; i < this.mustList.length; i++) {
        const item = this.mustList[i]
        if (!this.form[item.value] && item.condition()) {
          this.toast(item.placeholder)
          return false
        }
      }
      const vehicleList = this.form.orderVehicleList.filter(item => { return item.vehicleType == 0 })
      for (let i = 0; i < vehicleList.length; i++) {
        const item = vehicleList[i]
        item.payWay = this.form.payWay
        if (!item.vehicleId) {
          this.toast('请选择车辆')
          return false
        }
		
        if (item.driverType != 2 && !item.driverId) {
          this.toast('请选择司机')
          return false
        }
		if(!numericTypeCheck(item.realPrice,'车费请输入最多两位小数的数据类型')){
			return false
		}
		if(!numericTypeCheck(item.passengers,'乘车人数请输入最多两位小数的数据类型')){
			return false
		}
		if(!numericTypeCheck(item.driverSubsidyAmount,'司机补助请输入最多两位小数的数据类型')){
			return false
		}
		if (item.driverSubsidyAmount && item.driverSubsidyAmount > 99999) {
		  this.toast('司机补助请输入最大5位数')
		  return false
		}
        if (item.driverType == 2 && !item.driverName) {
          this.toast('请填写司机姓名')
          return false
        }
        if (!item.realPrice) {
          this.toast('请输入车费')
          return false
        }
      }

      // 外调车辆校验
      const outwardVehicleList = this.form.orderVehicleList.filter(item => { return item.vehicleType == 1 })
      if (outwardVehicleList != undefined && outwardVehicleList != 'undefined') {
        for (let i = 0; i < outwardVehicleList.length; i++) {
          const item = outwardVehicleList[i]
          if (!item.autoCompanyName) {
            this.toast('请填写车队名称')
            return false
          }
          if (!item.realPrice) {
            this.toast('请填写车费')
            return false
          }
          if (item.payWay == 3 && !item.outwardRealPrice) {
            this.toast('请填写外调车辆费用')
            return false
          }
        }
      }

      if (!checkDate(this.form.startDate, this.form.endDate)) return false

      if (this.showProtocol && !this.isRead) {
        this.toast(`请阅读并勾选《${this.name}司机协议》`)
        return false
      }
      return true
    },
    // 关联司机
    async bindLinkDriver(item) {
      const [err, res] = await bindDriver({
        driverId: item.driverId,
        vehicleId: item.vehicleId
      })
      if (!this.$http.errorCheck(err, res)) {
        this.canCreate = true
        return false
      }
    },
    async request(api, data, fn) {
      const [err, res] = await api(data)
      if (!this.$http.errorCheck(err, res)) {
        this.canCreate = true
        return false
      }
      const msg = res.data.data
      if (!msg.status && msg.popupType == 1) {
        this.toast(msg.message)
        this.canCreate = true
      } else {
        if (fn) fn()
      }
    },
    // 下单
    async addOrder() {
      const type = this.form.isTaoTuan ? 6 : 1
      const param = this.copyData(this.form)
	  param.productId = this.productId
      if (param.stopSite && param.stopSite.length > 0) {
        param.stopSite = param.stopSite.join(',')
      } else {
        param.stopSite = ''
      }
      // 拆分自有车辆和外调车辆
      param.outwardVehicleList = param.orderVehicleList.filter(item => { return item.vehicleType == 1 })
      param.orderVehicleList = param.orderVehicleList.filter(item => { return item.vehicleType == 0 })
	  param.taoTuan = param.isTaoTuan ? 1 : 0
      const [err, res] = await addInternalJson(Object.assign(param, { type }))
      this.loading.hide()
      if (!this.$http.errorCheck(err, res)) return false
      this.toast('订单提交成功', () => {
        this.setOrderIndex(0)
        this.jump('/pages/order/order', 'switchTab')
      })
    },
    // 获取获客订单详情
    async getHookOrder() {
      const date = {
        id: this.hookId
      }
      const [err, res] = await getHookOrderDetail(date)
      if (!this.$http.errorCheck(err, res)) return false
      const info = res.data.data
      const obj = {}
      Object.keys(this.form).forEach(key => {
        if (key !== 'orderVehicleList' && info[key]) {
          obj[key] = info[key]
        }
      })
      obj.customerPhone = info.creatorPhone
      obj.username = info.creatorName
      obj.companyHookOrderId = info.id
      obj.payWay = 3
      this.form.orderVehicleList[0].passengers = info.passengers
      Object.assign(this.form, obj)
    },
    ...mapMutations({
	  setSelectedFromTo: 'order/setSelectedFromTo',
      setChooseVehicleInfo: 'order/setChooseVehicleInfo',
      setChooseDriverInfo: 'order/setChooseDriverInfo',
      setOrderIndex: 'order/setOrderIndex'
    })
  }
}
</script>

<style scoped lang="scss">

.add-new-container{
  padding:30rpx 30rpx 14rpx;
}

.customer-module{
  overflow: visible;
}
</style>
